package cn.kgc.servlet;

import cn.kgc.pojo.Users;
import cn.kgc.service.UsersService;
import cn.kgc.service.impl.UsersServiceImpl;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

//接收用户提交的的用户名和密码，去数据库查询有没有这个用户，如果没有，跳转返回登录页面。如果有，跳转到新闻列表页面
public class LoginServlet extends HttpServlet{
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request,response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String userName = request.getParameter("userCode");
        String password = request.getParameter("userPassword");
        //调用UserService的方法（根据用户名和密码查询有没有该用户 select count(1) from news_user where username=? and password=? ）
        UsersService usersService = new UsersServiceImpl();
        Users users = new Users();
        users.setUserName(userName);
        users.setPassword(password);
        int flag = usersService.isUserExists(users);
        System.out.println(flag);
        if (flag > 0){
            request.getSession().setAttribute("users", users);
            response.sendRedirect("/news/jsp/admin/admin.jsp");
        }else {
            //登录失败
            request.getSession().setAttribute("errormsg", "用户名或密码错误！");
            response.sendRedirect("/news/jsp/login.jsp");
        }
    }
}
